import type { App } from 'vue';
import { CommonStore } from '@/store/index';
import _ from 'lodash';

interface IDirective {
  vDiscontinu: true;
}

/**
 * vscode识别类型
 */
declare module '@vue/runtime-core' {
  interface ComponentCustomProperties extends IDirective {}
}

export default {
  install(app: App) {
    /**
     * @description 禁止连续点击
     * @param {String} 参数名 参数描述
     * @reference
     */
    app.directive('discontinu', {
      mounted(el, binding, vnode, prevVnode) {
        const commonStore = CommonStore();
        (el as HTMLElement).addEventListener('click', function () {
          if (commonStore.$state.loadingIdList.length && binding.value) {
            el.style.pointerEvents = 'none';
            el.style.cursor = 'not-allowed';
            setTimeout(() => {
              el.style.pointerEvents = 'unset';
              el.style.cursor = 'unset';
            }, 300);
          }
        });
      },
    });

    const renderCellCacheMap = {};
    const setTdHeight = (el, length, goodLength) => {
      el.parentNode.style.height = Math.max(length * 36, goodLength * 36) + 'px';
      el.style.height = Math.max(length * 36, goodLength * 36) + 'px';
    };
    app.directive('fit-content-height', {
      created(el, binding, vnode, prevVnode) {
        let { length, goodLength, id, dispatch } = binding?.value;
        if (!dispatch) return;
        if (!renderCellCacheMap[id]) {
          renderCellCacheMap[id] = _.debounce(setTdHeight, 100, {
            leading: false,
            trailing: true,
          });
        }
        if (renderCellCacheMap[id]) renderCellCacheMap[id](el, length, goodLength);
        // 下面会介绍各个参数的细节
      },
      /* 自定义指令钩子 */
      updated(el, binding, vnode, prevVnode) {
        let { length, goodLength, id, dispatch } = binding?.value;
        if (!dispatch) return;
        if (!renderCellCacheMap[id]) {
          renderCellCacheMap[id] = _.debounce(setTdHeight, 100, {
            leading: false,
            trailing: true,
          });
        }

        renderCellCacheMap[id](el, length, goodLength);
      },
    });
  },
};
